from random import randint

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from meiduo_mall.libs.yuntongxun.sms import CCP
import logging
from rest_framework import status
from . import constants
from celery_tasks.sms.tasks import send_sms_code

logger = logging.getLogger('django')


# Create your views here.
class SMSCodeView(APIView):
    """短信验证码"""

    def get(self, request, mobile):
        # 1.创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')
        # 先从redis中获取此手机号是否发送过标记
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        # 如果取到了标记，就说明此手机号频繁发送短信
        # if send_flag:
        #     return Response({'message': '短信发送频繁！'}, status=status.HTTP_400_BAD_REQUEST)

        # 2.生成验证码
        sms_code = '%06d' % randint(0, 999999)
        logger.info(sms_code)

        # 创建redis管道（把多次redis操作装入管道中，将来一次性去执行，减少redis连接操作）
        pl = redis_conn.pipeline()
        # 3.把验证码存储到redis数据库
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 3.1 存储一个标记，表示此手机号已发送过短信，有效期60S
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 执行管道
        pl.execute()

        # 4.通过容联云通讯发送短信验证码
        # result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], 1)
        send_sms_code.delay(mobile, sms_code)

        # 5.响应
        return Response({'message': 'ok'})
